<?php

namespace App\Http\Controllers\Business;

use App\Http\Controllers\Controller;
use App\Models\Business\ComplainType;
use App\Common\Traits\Model\ModelSearchTrait;
use Illuminate\Http\Request;

class ComplainTypeController extends Controller
{
    use ModelSearchTrait;

    //
    public function index(Request $request, ComplainType $complainType)
    {
        $complainType=$this->singleModelSearch($request,$complainType,$this->complainCondition());
        $complains=$complainType->orderByDesc('updated_at')->paginate($request->size??20)->withQueryString();
        return $this->success($complains);
    }

    //
    public function complainCondition()
    {
        return [
            ['type_name','like'],
        ];
    }

    //
    public function store(Request $request)
    {
        if(!$request->filled('type_name')){
            return $this->failed('类型名称不能为空',201);
        }
        $data=['type_name'=>mb_substr($request->type_name,0,64)];
        ComplainType::create($data);
        return $this->success(['msg'=>'添加成功']);
    }

    //
    public function show(Request $request)
    {
        $type=ComplainType::find($request->complain_type_id??0);
        return $this->success($type);
    }

    //
    public function update(Request $request, ComplainType $complainType)
    {
        if(!$request->filled('type_name')){
            return $this->failed('类型名称不能为空',201);
        }
        $complain=$complainType->find($request->complain_type_id??0);
        if(empty($complain)){
            return $this->failed('id错误，无此类型',201);
        }
        $complain->type_name=mb_substr($request->type_name,0,64);
        $complain->save();
        return $this->success(['msg'=>'编辑成功']);
    }

    //
    public function destroy(Request $request, ComplainType $complainType)
    {
        $complain=$complainType->find($request->complain_type_id??0);
        if(empty($complain)){
            return $this->failed('id错误，无此类型',201);
        }
        $complain->delete();
        return $this->success(['msg'=>'删除成功']);
    }

    //
    public function getAllComplains(){
        $complains=ComplainType::all();
        return $this->success($complains);
    }


}
